﻿using System.IO;

using System.Net.DnsToolkit.Packet;
using System.Net.DnsToolkit.Util;
using System.Net.DnsToolkit.Serializer;
using System.Net.DnsToolkit.TestUnit.Helper;
using System.Net.DnsToolkit.Serializer.Stream.Compression;

namespace System.Net.DnsToolkit.TestUnit.Helper {

    public class PacketHelper {


        /// <summary>
        /// Convert a hexa string into DNS Message
        /// </summary>
        /// <param name="packet"></param>
        /// <returns></returns>
        internal static IMessage Read(string packet) {

            if (string.IsNullOrEmpty(packet)) {
                throw new ArgumentNullException("packet");
            }
            byte[] bs = BitStringHelper.StringToByteArray(packet);
            var stream = new MemoryStream(bs);
            IMessage message = null;
            DnsReader.TryRead(stream, out message);
            return message;

        }

        /// <summary>
        /// Convert DNS Message into a hexa string
        /// </summary>
        /// <param name="packet"></param>
        /// <returns></returns>
        internal static string Write(IMessage message) {

            if (message == null) {
                throw new ArgumentNullException("message");
            }

            return Write(message, true);
        }

        internal static string Write(IMessage message, bool useCompression) {

            if (message == null) {
                throw new ArgumentNullException("message");
            }

            var stream2 = new MemoryStream();
            DnsWriter.Write(stream2, message, useCompression);
            byte[] bs2 = stream2.ToArray();
            string packet = BitStringHelper.ByteArrayToString(bs2);
            return packet;

        }

    }
}
